import math
from torch.utils.data import Dataset, DataLoader, random_split
from torch import Tensor, nn, optim
import torch

class DatasetLSTMForLearningPurposes(Dataset):

    def __init__(self, T = 50, input_size = 100, sample_total = 1000):
        self.T = T
        self.total = sample_total + input_size
        self.time_series = []
        for i in range(self.total):
            x = i
            y = math.sin(2 * math.pi * 1 / T * x) * 0.7
            self.time_series.append([y])
        self.input_size = input_size
        self.sample_total = sample_total

    def __len__(self):
        return self.sample_total

    def __getitem__(self, idx):
        network_input = self.time_series[idx:(idx + self.input_size)]
        network_output = self.time_series[(idx + 1):(idx + 1 + self.input_size)]
        return Tensor(network_input), Tensor(network_output)

class MyLSTM(nn.Module):

    def __init__(self, input_items = 100, input_item_size = 1, output_item_size = 1):
        super().__init__()
        self.input_items = input_items
        self.input_item_size = input_item_size
        self.output_item_size = output_item_size
        hidden_size = 1 # 相当于输出维度
        num_layers = 3
        input_size = 1 # 不是序列长度，而是一个输入项有几个元素
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)

    def forward(self, input_data):
        lstm_out, _ = self.lstm(input_data)
        return lstm_out

def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        pred = model(X)
        loss = loss_fn(pred, y)

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        if batch % 6 == 0:
            loss, current = loss.item(), (batch) * dataloader.batch_size + len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

def test(dataloader, model, loss_fn):
    model.eval()
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss = 0
    with torch.no_grad():
        for X, y in dataloader:
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
    test_loss /= num_batches
    print(f"Test Avg loss: {test_loss:>8f} \n")

if __name__ == '__main__':

    batch_size = 64
    train_data_size = 800
    test_data_size = 200

    dataset_object = DatasetLSTMForLearningPurposes(30, 7, train_data_size + test_data_size)
    train_data, test_data = random_split(dataset_object, [train_data_size, test_data_size])

    model = MyLSTM(7)

    train_data_loader = DataLoader(train_data, batch_size=batch_size)
    test_data_loader = DataLoader(test_data, batch_size=batch_size)

    loss_fn = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    epochs = 500
    for t in range(epochs):
        print(f"Epoch {t+1}\n-------------------------------")
        train(train_data_loader, model, loss_fn, optimizer)
        test(test_data_loader, model, loss_fn)
    print("Done!")

    torch.save(model.state_dict(), "model.pth")
    print("Saved PyTorch Model State to model.pth")
